import socket
import netifaces

def get_broadcast_addresses():
    broadcasts = []
    for iface in netifaces.interfaces():
        addrs = netifaces.ifaddresses(iface)
        if netifaces.AF_INET in addrs:
            for link in addrs[netifaces.AF_INET]:
                if 'broadcast' in link:
                    broadcasts.append(link['broadcast'])
    return broadcasts

def send_broadcast_message(message: str, port: int =23456):
    broadcasts = get_broadcast_addresses()
    if not broadcasts:
        print("未找到广播地址。")
        return

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

    for bc_addr in broadcasts:
        try:
            sock.sendto(message.encode('utf-8'), (bc_addr, port))
            print(f"向广播地址 {bc_addr}:{port} 发送消息成功。")
        except Exception as e:
            print(f"向广播地址 {bc_addr}:{port} 发送失败，错误：{e}")

if __name__ == "__main__":
    msg = "这是一个测试广播包"
    send_broadcast_message(msg)
